package com.wzt.lianfirecontrol.fragment.baojingfuhe;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.baojingfuhe.BaoJingCheckModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.MinioUtils;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.ScreenUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;

import java.io.File;
import java.util.HashMap;

public class WuBaoFragment extends BaseFragment {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private View include_progress_bar;

    private TextView tv_title;
    private EditText et_reason;// 误报原因
    private TextView tv_text_num;

    private LinearLayout ll_device_three_photo;
    private View include_play_photo_three;
    private RelativeLayout rl_device_photo_1;
    private ImageView iv_device_photo_1;
    private ImageView iv_photo_delete_1;
    private RelativeLayout rl_device_photo_2;
    private ImageView iv_device_photo_2;
    private ImageView iv_photo_delete_2;
    private RelativeLayout rl_device_photo_3;
    private ImageView iv_device_photo_3;
    private ImageView iv_photo_delete_3;

    private Button bt_submit;

    private static final int SUBMIT_DETAIL_WHAT = 0;
    private static final int ZHENGJING_SUBMIT_WHAT = 1;

    private String[] imgUrl = new String[]{"", "", ""};
    private boolean isUpdateImg = false;
    private boolean isSubmitSuccess = false;

    private BaoJingCheckModel baoJingFuHeModel;

    private boolean isZhenJing = false;

    private Dialog call119Dialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            if (null != bundle && bundle.containsKey("model")){
                baoJingFuHeModel = (BaoJingCheckModel) bundle.getSerializable("model");
                isZhenJing = bundle.getBoolean("isZhenjing", false);
            }
            if (null == baoJingFuHeModel){
                activity.finish();
            }
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_wubao, container, false);
            initView();
            PreferencesUtils.putString(activity, ConstData.WUBAOREFRESH, "1");
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        tv_title = itemContentView.findViewById(R.id.tv_title);
        if (isZhenJing){
            tv_title.setText("火警描述");
        }
        et_reason = itemContentView.findViewById(R.id.et_reason);
        if (isZhenJing) {
            et_reason.setHint("请详细描述火警情况");
        }
        tv_text_num = itemContentView.findViewById(R.id.tv_text_num);
        et_reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (StringUtils.isEmpty(et_reason.getText().toString())){
                    tv_text_num.setText("0/100");
                }else {
                    tv_text_num.setText(et_reason.getText().toString().length() + "/100");
                }

            }
        });

        initPhotoThree();

        bt_submit = itemContentView.findViewById(R.id.bt_submit);
        if (isZhenJing) {
            bt_submit.setText("火警一键上报");
        }
        bt_submit.setVisibility(View.VISIBLE);
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 提交
                if (isZhenJing){
                    initZhenJingHttpHelper();
                }else {
                    initAddDetailHttpHelper();
                }
            }
        });

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
    }

    private void initPhotoThree() {
        include_play_photo_three = itemContentView.findViewById(R.id.include_play_photo_three);
        rl_device_photo_1 = itemContentView.findViewById(R.id.rl_device_photo_1);
        iv_device_photo_1 = itemContentView.findViewById(R.id.iv_device_photo_1);
        iv_photo_delete_1 = itemContentView.findViewById(R.id.iv_photo_delete_1);
        rl_device_photo_2 = itemContentView.findViewById(R.id.rl_device_photo_2);
        iv_device_photo_2 = itemContentView.findViewById(R.id.iv_device_photo_2);
        iv_photo_delete_2 = itemContentView.findViewById(R.id.iv_photo_delete_2);
        rl_device_photo_3 = itemContentView.findViewById(R.id.rl_device_photo_3);
        iv_device_photo_3 = itemContentView.findViewById(R.id.iv_device_photo_3);
        iv_photo_delete_3 = itemContentView.findViewById(R.id.iv_photo_delete_3);

        int width = (ScreenUtils.getScreenWidth(activity) - Utils.dip2px(activity, 90)) / 3;
        rl_device_photo_1.getLayoutParams().width = width;
        rl_device_photo_1.getLayoutParams().height = width;
        rl_device_photo_2.getLayoutParams().width = width;
        rl_device_photo_2.getLayoutParams().height = width;
        rl_device_photo_3.getLayoutParams().width = width;
        rl_device_photo_3.getLayoutParams().height = width;

        iv_device_photo_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                if (StringUtils.isEmpty(imgUrl[0])){
                    addImageOrPlayPhoto(ConstData.PHOTO_DEVICE_LIST_1, false);
                }else {
                    ((ShowFragActivity)activity).setShowImg(imgUrl[0]);
                }
            }
        });
        iv_photo_delete_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                MinioUtils.removeFile(activity, imgUrl[0], handler);
                imgUrl[0] = "";
                updateImageView();
            }
        });

        iv_device_photo_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                if (StringUtils.isEmpty(imgUrl[1])){
                    addImageOrPlayPhoto(ConstData.PHOTO_DEVICE_LIST_2, false);
                }else {
                    ((ShowFragActivity)activity).setShowImg(imgUrl[1]);
                }
            }
        });
        iv_photo_delete_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                MinioUtils.removeFile(activity, imgUrl[1], handler);
                imgUrl[1] = "";
                updateImageView();
            }
        });

        iv_device_photo_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                if (StringUtils.isEmpty(imgUrl[2])){
                    addImageOrPlayPhoto(ConstData.PHOTO_DEVICE_LIST_3, false);
                }else {
                    ((ShowFragActivity)activity).setShowImg(imgUrl[2]);
                }
            }
        });
        iv_photo_delete_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateImg){
                    ToastUtils.showToast(activity, "正在上传图片");
                    return;
                }
                MinioUtils.removeFile(activity, imgUrl[2], handler);
                imgUrl[2] = "";
                updateImageView();
            }
        });
        updateImageView();
    }

    /**
     * 添加列表
     */
    private void initAddDetailHttpHelper() {
        if (!Utils.hasNetwork(activity)){
            ToastUtils.showToast(activity, "网络未连接");
            return;
        }
        if (isUpdateImg){
            ToastUtils.showToast(activity, "正在上传图片");
            return;
        }


        HashMap<String, Object> hashMap = new HashMap<>();

        if (StringUtils.isEmpty(et_reason.getText().toString())){
//            ToastUtils.showToast(activity, "未输入误报原因");
//            return;
            hashMap.put("remark", et_reason.getText().toString());
        }else {
            hashMap.put("remark", et_reason.getText().toString());
        }
        hashMap.put("id", baoJingFuHeModel.getId());

        StringBuilder stringBuilder = new StringBuilder();
        if (!StringUtils.isEmpty(imgUrl[0])) {
            stringBuilder.append(imgUrl[0]);
        }
        if (!StringUtils.isEmpty(imgUrl[1])) {
            stringBuilder.append("," + imgUrl[1]);
        }
        if (!StringUtils.isEmpty(imgUrl[2])) {
            stringBuilder.append("," + imgUrl[2]);
        }
        hashMap.put("imgUrls", stringBuilder.toString());
        hashMap.put("userId", UserInfoModel.getUserInfo(activity).getId());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        include_progress_bar.setVisibility(View.VISIBLE);
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.BJ_FUHE_FALSE, SUBMIT_DETAIL_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 添加列表
     */
    private void initZhenJingHttpHelper() {
        if (!Utils.hasNetwork(activity)){
            ToastUtils.showToast(activity, "网络未连接");
            return;
        }
        if (isUpdateImg){
            ToastUtils.showToast(activity, "正在上传图片");
            return;
        }

        HashMap<String, Object> hashMap = new HashMap<>();

        if (StringUtils.isEmpty(et_reason.getText().toString())){

        }else {
            hashMap.put("remark", et_reason.getText().toString());
        }
        hashMap.put("id", baoJingFuHeModel.getId());

        StringBuilder stringBuilder = new StringBuilder();
        if (!StringUtils.isEmpty(imgUrl[0])) {
            stringBuilder.append(imgUrl[0]);
        }
        if (!StringUtils.isEmpty(imgUrl[1])) {
            stringBuilder.append("," + imgUrl[1]);
        }
        if (!StringUtils.isEmpty(imgUrl[2])) {
            stringBuilder.append("," + imgUrl[2]);
        }
        hashMap.put("imgUrls", stringBuilder.toString());
        hashMap.put("userId", UserInfoModel.getUserInfo(activity).getId());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        include_progress_bar.setVisibility(View.VISIBLE);
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.BJ_FUHE_TRUE, ZHENGJING_SUBMIT_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }



    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case SUBMIT_DETAIL_WHAT:

                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if ((!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE)))){
            include_progress_bar.setVisibility(View.GONE);
            if (msg.what == SUBMIT_DETAIL_WHAT && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                PreferencesUtils.putString(activity, ConstData.NEEDFUHEREFRESH, "0");
                PreferencesUtils.putString(activity, ConstData.WUBAOREFRESH, "0");
                isSubmitSuccess = true;
                include_progress_bar.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        include_progress_bar.setVisibility(View.GONE);
                        activity.finish();
                    }
                }, 1000);

            }else if (msg.what == ZHENGJING_SUBMIT_WHAT && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                PreferencesUtils.putString(activity, ConstData.NEEDFUHEREFRESH, "0");
                PreferencesUtils.putString(activity, ConstData.WUBAOREFRESH, "0");
                call119Dialog = DialogUtils.createSureAndCancelDialog(activity, "是否拨打119", "取消", "确认",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                include_progress_bar.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        include_progress_bar.setVisibility(View.GONE);
                                        activity.finish();
                                    }
                                }, 1000);
                                // 取消
                                DialogUtils.closeDialog(call119Dialog);
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtils.closeDialog(call119Dialog);
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setActionType(ConstData.PHONE);
                                bannerModel.setActionValue("119");
                                activity.setClickAction(bannerModel);
                                include_progress_bar.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        include_progress_bar.setVisibility(View.GONE);
                                        activity.finish();
                                    }
                                }, 1000);

                            }
                        });
                DialogUtils.showDialog(call119Dialog);
            }
            if (msg.what >= ConstData.COMMIT_IMG_WHAT){
                isUpdateImg = false;
            }
            return;
        }
        switch (msg.what){
            case SUBMIT_DETAIL_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                isSubmitSuccess = true;
                activity.finish();
                break;
        }
        if (msg.what >= ConstData.COMMIT_IMG_WHAT){
            isUpdateImg = false;
            include_progress_bar.setVisibility(View.GONE);
            switch (msg.what - ConstData.COMMIT_IMG_WHAT){
                case ConstData.PHOTO_DEVICE_LIST_1:
                    imgUrl[0] = bundle.getString("fileName");
                    break;
                case ConstData.PHOTO_DEVICE_LIST_2:
                    imgUrl[1] = bundle.getString("fileName");
                    break;
                case ConstData.PHOTO_DEVICE_LIST_3:
                    imgUrl[2] = bundle.getString("fileName");
                    break;
            }
            updateImageView();
        }
    }

    /**
     * 跳转拍照和相册
     * @param photoWhat
     * @param isPlayPhoto
     */
    public void addImageOrPlayPhoto(int photoWhat, boolean isPlayPhoto){
        if (activity instanceof ShowFragActivity) {
            if (isPlayPhoto) {
                ((ShowFragActivity)activity).skipToPlayPhoto(photoWhat);
            } else {
                ((ShowFragActivity)activity).initSubmitPicView(photoWhat);
            }
        }
    }

    @Override
    public void imgSuccessAction(File file, String img, int photoWhat) {
        super.imgSuccessAction(file, img, photoWhat);
        commitPic(file, photoWhat, img);
    }

    /**
     * 提交图片
     * @param file
     * @param what
     */
    private void commitPic(final File file, final int what, final String img){
        isUpdateImg = true;
        include_progress_bar.setVisibility(View.VISIBLE);
        MinioUtils.upLoadFile(activity, what, file, handler);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!isSubmitSuccess){
            for (int i = 0; i < imgUrl.length; i++){
                if (!StringUtils.isEmpty(imgUrl[i])){
                    MinioUtils.removeFile(activity, imgUrl[i], handler);
                }
            }
        }
        DialogUtils.closeDialog(call119Dialog);
    }

    private void updateImageView(){
        updateImageUrl();
        int size = 0;
        for (int i = 0; i < imgUrl.length; i++){
            if (!StringUtils.isEmpty(imgUrl[i])){
                size++;
            }
        }
        switch (size){
            case 3:
                rl_device_photo_1.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_1, imgUrl[0]);
                iv_photo_delete_1.setVisibility(View.VISIBLE);

                rl_device_photo_2.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_2, imgUrl[1]);
                iv_photo_delete_2.setVisibility(View.VISIBLE);

                rl_device_photo_3.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_3, imgUrl[2]);
                iv_photo_delete_3.setVisibility(View.VISIBLE);
                break;
            case 2:
                rl_device_photo_1.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_1, imgUrl[0]);
                iv_photo_delete_1.setVisibility(View.VISIBLE);

                rl_device_photo_2.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_2, imgUrl[1]);
                iv_photo_delete_2.setVisibility(View.VISIBLE);

                rl_device_photo_3.setVisibility(View.VISIBLE);
                iv_device_photo_3.setImageResource(R.mipmap.icon_duty_detail_photo_big);
                iv_photo_delete_3.setVisibility(View.INVISIBLE);
                break;
            case 1:
                rl_device_photo_1.setVisibility(View.VISIBLE);
                GildeUtils.loadImageCorner(activity, iv_device_photo_1, imgUrl[0]);
                iv_photo_delete_1.setVisibility(View.VISIBLE);

                rl_device_photo_2.setVisibility(View.VISIBLE);
                iv_device_photo_2.setImageResource(R.mipmap.icon_duty_detail_photo_big);
                iv_photo_delete_2.setVisibility(View.INVISIBLE);

                rl_device_photo_3.setVisibility(View.INVISIBLE);
                break;
            case 0:
                rl_device_photo_1.setVisibility(View.VISIBLE);
                iv_device_photo_1.setImageResource(R.mipmap.icon_duty_detail_photo_big);
                iv_photo_delete_1.setVisibility(View.INVISIBLE);

                rl_device_photo_2.setVisibility(View.INVISIBLE);

                rl_device_photo_3.setVisibility(View.INVISIBLE);
                break;
        }
    }

    /**
     * 调整图片链接顺序
     */
    private void updateImageUrl(){
        if (null != imgUrl && imgUrl.length > 0){
            for (int i = 0; i < imgUrl.length; i++){
                if (StringUtils.isEmpty(imgUrl[i])){
                    for (int j = i + 1; j < imgUrl.length; j++){
                        if (!StringUtils.isEmpty(imgUrl[j])){
                            imgUrl[i] = imgUrl[j];
                            imgUrl[j] = "";
                            break;
                        }
                    }
                }
            }
        }
    }
}
